package com.baizhi.cmfz.config;

import com.baizhi.cmfz.realm.AuthenRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Shiro配置类
 *
 * @author zhanglh
 * @date 2019/09/25
 */
@Configuration
public class ShiroConfig {

    /**
     * 配置过滤器工厂
     *
     * @param securityManager 安全管理器
     * @return shiro过滤器工厂类
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //配置拦截规则 过滤器链
        Map<String, String> map = new HashMap<>();
        //anon 放行，不拦截
        map.put("/login.jsp", "anon");
        map.put("/admin/login", "anon");
        map.put("/admin/getCaptcha", "anon");
        //authc 拦截
        map.put("/main.jsp", "authc");
        map.put("/jsp/*", "authc");
        //应用拦截规则
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置一个安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }

    /**
     * 创建安全管理器
     *
     * @param authenRealm 自定义认证
     * @return 安全管理器
     */
    @Bean
    public SecurityManager getSecurityManager(AuthenRealm authenRealm) {
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        //设置realm
        defaultSecurityManager.setRealm(authenRealm);
        return defaultSecurityManager;
    }

    /**
     * 创建Realm
     *
     * @return Realm
     */
    @Bean
    public AuthenRealm getRealm() {
        return new AuthenRealm();
    }
}
